<template>
  <div class="wangEditor" :class="{ isReviewWangEditor: isReview }">
    <div class="toolBar" :id="`${'toolBar-' + editId}`"></div>
    <div class="editContent" :id="`${'edit-' + editId}`"></div>
    <span class="WEcopyBtn" @click="handleCopy" v-if="isReview">复制</span>
  </div>
</template>

<script>
import wangEditor from "wangeditor";
import { location, location_QuestionBank, copy } from "@/util/tool";
import { encryptionToString } from "@/util/qetag";
import { mapState } from "vuex";
export default {
  data() {
    return {
      editor: null,
    };
  },
  props: {
    editId: String || Number,
    placeholder: String,
    menus: {
      type: Array,
      default: () => [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "underline", // 下划线
        "foreColor", // 文字颜色
        "justify", // 对齐方式
        "image", // 插入图片
        "video", // 插入视频
        "link", // 链接
        "undo", // 撤消
        "redo", // 重复
      ],
    },
    value: String,
    disabled: Boolean,
    isReview: Boolean,
    isInit: Boolean,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    disabled(newValue) {
      this.editor.$textElem.attr("contenteditable", !newValue);
    },
    placeholder(newValue, oldValue) {
      if (oldValue && newValue) {
        this.editor.config.placeholder = this.placeholder;
        document.getElementsByClassName("placeholder")[0].innerHTML =
          this.placeholder;
      }
    },
  },
  methods: {
    // 创建简答题的富文本编辑器
    createEdit() {
      const _that = this;
      const antdMessage = this.$antdMessage;

      this.editor = null;
      this.editor = new wangEditor(
        `${"#toolBar-" + this.editId}`,
        `${"#edit-" + this.editId}`
      );

      // onchange回调时间 无效
      // this.editor.config.onchangeTimeout = 500
      // 内容修改回调
      this.editor.config.onchange = function (newHtml) {
        _that.getEditorData();
      };
      // 设置菜单
      this.editor.config.menus = _that.menus;
      // // 失去焦点
      // this.editor.config.onblur = (newHtml) => {
      //   _that.getEditorData();
      // };
      
      if (!_that.menus || _that.menus.indexOf('image') !== -1){
        /**
         * @params
         *  uploadImgServer 配置api接口
         *  withCredentials 跨域携带cookie
         *  uploadImgParams 请求头参数
         *  customUploadImg 回调函数
         */
  
        // 使用 base64 保存图片
        // this.editor.config.uploadImgShowBase64 = true
        this.editor.config.uploadImgServer = "/f_api/utils/uploadfiles";
        this.editor.config.withCredentials = true;
        this.editor.config.uploadImgParams = {
          Accept: "application/json",
        };
        this.editor.config.customUploadImg = async function (
          resultFiles,
          insertImgFn
        ) {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          // let nFormData = new FormData();
          let hashArray = [];
          for (let item of resultFiles) {
            // 文件名
            let fileName = item.name;
            // 过滤英文分号
            if (item.name.indexOf(";") !== -1) {
              fileName = item.name.replace(/;/g, "");
            }
  
            let hash = await encryptionToString({ raw: item });
            if (hash === "Fto5o-5ea0sNMlW_75VgGJCv2AcJ") {
              this.$antdMessage.error({
                content: "文件读取错误！",
              });
              return;
            }
            if (hash) hashArray.push(hash);
            _that.$emit('uploadImage', item, hash, _that.uploadImageIniserToHtml, _that, insertImgFn)
            console.log(insertImgFn);
          }
        };
      }

      this.editor.txt.eventHooks.linkClickEvents.push(this.link);
      // 自动获取焦点
      this.editor.config.focus = false;
      // 隐藏tooltips菜单
      this.editor.config.showMenuTooltips = true;
      // 文本提示
      this.editor.config.placeholder = this.placeholder;
      // 创建编辑器
      this.editor.create();
      // 设置内容
      if (_that.value) {
        let newValue = _that.value;
        // const A_Html = newValue.match(/<a href="(.+?)">(.+?)<\/a>/gi);
        // if (A_Html) {
        //   A_Html.forEach((item, index) => {
        //     newValue = newValue.replace(item, `#R#E#P#L#${index}#A#C#E#`);
        //   });
        //   newValue = this.formatHTML(newValue);
        //   A_Html.forEach((item, index) => {
        //     newValue = newValue.replace(`#R#E#P#L#${index}#A#C#E#`, item);
        //   });
        // }
        // this.editor.$textElem.elems[0].innerHTML = `<p data-we-empty-p>${newValue}</p>`;
        this.editor.$textElem.elems[0].innerHTML = newValue;
      } else {
        this.editor.txt.append(`<p data-we-empty-p><br></p>`);
      }
      // 禁用编辑器
      if (this.disabled) {
        this.editor.$textElem.attr("contenteditable", false);
      }
    },
    getEditorData() {
      // 如果还没初始化 或 编辑器不存在 则 返回
      if (!this.editor) return;
      // 获取编辑器内容
      // let data = this.htmlDecodeByRegExp(this.editor.txt.html()).replace(/(^<p>*)|(<\/p>*$)/g, "","");
      let data = this.editor.txt.html();
      let text = this.editor.txt.text();
      this.$emit("change", {
        data: data,
        id: this.editId,
        text,
        // decodeText: this.htmlDecodeByRegExp(data).replace("<p data-we-empty-p><br>", "").replace("<p>", "").replace("</p>", "")
      });
    },
    link(data) {
      if (this.disabled && data.selector.nodeName === "A") {
        window.open(data.selector.href);
      }
    },
    formatHTML(a) {
      return new Option(a).innerHTML;
    },
    /*4.用正则表达式实现html解码（反转义）*/
    htmlDecodeByRegExp(str) {
      var temp = "";
      if (str.length == 0) return "";
      temp = str.replace(/&amp;/g, "&");
      temp = temp.replace(/&lt;/g, "<");
      temp = temp.replace(/&gt;/g, ">");
      temp = temp.replace(/&nbsp;/g, " ");
      // temp = temp.replace(/&nbsp;/g, "%C2%A0"); // 特殊空格
      temp = temp.replace(/&#39;/g, "'");
      temp = temp.replace(/&quot;/g, '"');
      temp = temp.replace(/<br\/>/g, "\n");
      temp = temp.replace(/\t/g, "");
      return temp;
    },
    handleCopy() {
      // 特殊空格解码
      let reg = new RegExp(decodeURIComponent("%C2%A0"), "g");
      copy(this.editor.$textElem.elems[0].innerText?.replace(reg, " "));
    },
    uploadImageIniserToHtml(res, _that, insertImgFn) {
      // let fileUrl = res.split("上传成功！文件地址分别为：")[1];
      let fileUrl = res.data.filePaths;
      if (fileUrl) {
        // 上传图片，返回结果，将图片插入到编辑器中
        fileUrl.forEach((item) => {
          let url = item.fileUrl
          insertImgFn(location(window) + res.data.baseFileUrl + url);
        });
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.createEdit();
    });
  },
};
</script>

<style lang="stylus">
.wangEditor {
  position: relative;
  border: solid 1px #707070;

  // padding-bottom: 20px;
  .w-e-text-container, .w-e-toolbar {
    z-index: unset !important;
  }

  .w-e-text-container {
    cursor: text;
    overflow: unset;
    background: none;
    word-wrap: break-word;
    overflow: hidden;
    overflow-y: auto;
    max-height: 150px;

    .w-e-text {
      min-height: 118px;

      a {
        color: #57b3ff;
      }

      a:hover {
        color: #008cff;
      }

      p {
        word-break: break-all;
      }
    }
  }

  .toolBar {
    border-bottom: solid 1px #707070;

    .w-e-menu .w-e-panel-container {
      z-index: 1000;
      top: -40px;

      .w-e-button-container {
        line-height: 1;
      }
    }
  }

  .editContent {
    min-height: 104px;
  }

  .WEcopyBtn {
    cursor: pointer;
    position: absolute;
    bottom: 0;
    right: 20px;
  }
}

.isReviewWangEditor {
  cursor: text;
  // font-family: Yu Gothic UI;
  font-size: 1rem;
  color: #003262;
  background: #fff;
  border-color: #E4E7ED;
  height: 118px !important;
  max-height: 118px;
  border-radius: 5px;

  .toolBar {
    display: none;
    border: none;
  }

  .w-e-text-container {
    .w-e-tooltip {
      display: none;
    }
  }
}
</style>